<?php
/**
 * Created by PhpStorm.
 * User: idcu
 * Date: 2016/3/10
 * Time: 9:21
 */
namespace Service\Controller;
use Think\Upload;
use Admin\Controller\AdminController;

class SmsController extends AdminController
{
    protected $searchRule = array(
        'tel' => array('/1\d*/','like','','%')
    );

    protected $modelName = 'Crm\SmsRecord';

    protected $uid = '23272980';
    protected $pwd = '8d91efee0350711027672437d1939548';

    public function send($mobile, $tpl, $param)
    {
        vendor("Dayu.TopSdk");
        $client = new \TopClient($this->uid, $this->pwd);
        $req = new \AlibabaAliqinFcSmsNumSendRequest();
        $req->setExtend("");
        $req->setSmsType("normal");
        $req->setSmsFreeSignName("青藤物业");
        $req->setSmsParam($param);
        $req->setRecNum($mobile);
        $req->setSmsTemplateCode($tpl);
        $resp = $client->execute($req, $sessionKey);
        return $resp;
    }

    public function sms()
    {
        $msg = array(
            'code' => '1234',
            'product' => '小徐'
        );
        $result = $this->send('18005750848', 'SMS_4260074', json_encode($msg));
        $this->ajaxReturn($result);
        $tpl = 'SMS_4260074';
        $arr = $this->getMsg();
        $result = array();
        foreach($arr as $k=>$v){
            $tel = $v['tel'];
            unset($v['tel']);
            $r = $this->send($tel, $tpl, json_encode($v));
            array_push($result,$r);
        }
        $this->ajaxReturn($result);
    }

    public function getTpl()
    {
        $req = I('param.');
        if($req['sno']){
            $param['sno'] = $req['sno'];
        }
        $this->ajaxReturn(D('Crm/SmsTpl')->where($param)->select());
    }

    public function index()
    {
        $this->display();
    }

    public function create(){
//        $tpl = D('Crm/SmsTpl')->select();
//        $this->assign('tpl',$tpl);
//        dump($tpl);
        $this->display();
    }

//    public function upload()
//    {
//        $config = array(
//            'maxSize' => 3145728,
//            'rootPath' => ZH_ROOT . '/Upload/',
//            'savePath' => 'sms',
//            'saveName' => array('uniqid', ''),
//            'exts' => array('xls','xlsx'),
//            'autoSub' => true,
//            'subName' => array('date', 'Ymd'),
//        );
//        $upload = new Upload($config);// 实例化上传类
//        // 上传文件
//        $info = $upload->upload();
//        $msg = array_shift($info);
//        $filepath =  ZH_ROOT . '/Upload/'.$msg['savepath'].$msg['savename'];
//        echo $filepath;
//        if (!$info) {// 上传错误提示错误信息
//            $req['stat'] = 0;
//            $req['msg'] = $upload->getError();
//            $this->ajaxReturn($req);
//        } else {// 上传成功
//            $req['stat'] = 1;
//            $req['msg'] = $info;
//            $this->ajaxReturn($req);
//        }
//    }

    public function getMsg($filePath)
    {
        Vendor('PHPExcel.PHPExcel', '', '.php');
//        $PHPExcel = new \PHPExcel();
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                echo 'no Excel';
                return;
            }
        }
        $PHPExcel = $PHPReader->load($filePath);
        /**读取excel文件中的第一个工作表*/
        $currentSheet = $PHPExcel->getSheet(0);
        /**取得最大的列号*/
        $allColumn = $currentSheet->getHighestColumn();
        /**取得一共有多少行*/
        $allRow = $currentSheet->getHighestRow();
        /**从第二行开始输出，因为excel表中第一行为列名*/
        $arr = array();
        $keys = array();
        for($currentRow = 1;$currentRow <= $allRow;$currentRow++){
            /**从第A列开始输出*/
            for($currentColumn= 'A';$currentColumn<= $allColumn; $currentColumn++){
                $val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue();/**ord()将字符转为十进制数*/
                if($currentRow == 1){
                    $keys[$currentColumn] = (string)$val;
//                    $keys[$currentColumn] = iconv('utf-8','gb2312', $val);
                }else{
                    $msg[$keys[$currentColumn]] = $currentColumn == 1 ? $val : (string)$val;
//                    $msg[$keys[$currentColumn]] = iconv('utf-8','gb2312', $val);
                }
//                if($currentColumn == 'A')
//                {
//                    $msg['tel'] = iconv('utf-8','gb2312', $val);
//                }elseif($currentColumn == 'B'){
//                    /**如果输出汉字有乱码，则需将输出内容用iconv函数进行编码转换，如下将gb2312编码转为utf-8编码输出*/
//                    $msg['code'] = iconv('utf-8','gb2312', $val);
//                }else{
//                    $msg['product'] = iconv('utf-8','gb2312', $val);
//                }
            }
            if($currentRow != 1){
                array_unshift($arr,$msg);
            }
        }
//        var_dump($arr);exit;
        return $arr;
    }

    public function excelSend(){
        $config = array(
            'maxSize' => 3145728,
            'rootPath' => ZH_ROOT . '/Upload/',
            'savePath' => 'sms',
            'saveName' => array('uniqid', ''),
            'exts' => array('xls','xlsx'),
            'autoSub' => true,
            'subName' => array('date', 'Ymd'),
        );
        $upload = new Upload($config);// 实例化上传类
        // 上传文件
        $info = $upload->upload();
        if(!$info){// 上传错误提示错误信息
            $req['stat'] = 0;
            $req['msg'] = $upload->getError();
            $this->ajaxReturn($req);
        }else{
            $msg = array_shift($info);
            $filePath = $config['rootPath'].$msg['savepath'].$msg['savename'];
        }
//        $tpl = 'SMS_4260074';
        $tpl = I('param.tpl');
        $arr = $this->getMsg($filePath);
        $result = array();
        foreach($arr as $k=>$v){
            $tel = $v['tel'];
            unset($v['tel']);
//            $v['product'] = (string)$v['product'];
//            $v['code'] = (string)$v['code'];
            $r = $this->send($tel, $tpl, json_encode($v));
            $data['tel'] = $tel;
            $data['tpl'] = $tpl;
            $data['content'] = json_encode($v);
            $data['time'] = time();
            $data['stat'] = $r->result->success ? 1 : 0;
            $data['request_id'] = $r->request_id;
            // 成功
            $data['err_code'] = $r->result->err_code;
            $data['model'] = $r->result->model;
            // 失败
            $data['code'] = $r->code;
            $data['msg'] = $r->msg;
            $data['sub_code'] = $r->sub_code;
            $data['sub_msg'] = $r->sub_msg;
            M('SmsRecord')->data($data)->add();
            array_push($result,$r);
        }
        $this->redirect('Sms/close', array(), 0, '页面跳转中...');
//        $this->ajaxReturn($result);
    }

    public function close(){
        $this->display();
    }

    public function search(){
        $req = I('param.');
        $req['tel'] ? $param['tel'] = $req['tel'] : $param = null;
        $page['pageIndex'] = $req['pageIndex'];
        $page['pageSize'] = $req['pageSize'];
        $data = M('SmsRecord')->where($param)->order(array('time'=>'desc'))->page($page['pageIndex'],$page['pageSize'])->select();
        if($data){
            foreach($data as $k=>$v){
                $data[$k]['time'] = date('Y-m-d H:i:s',$v['time']);
            }
            $res['stat'] = 1;
            $res['data'] = $data;
            $res['count'] = $data = M('SmsRecord')->where($param)->count();
            $res['msg'] = '查找到1条数据。';
        }elseif($data == null){
            $res['stat'] = 1;
            $res['data'] = array();
            $res['count'] = 0;
            $res['msg'] = '查找到0条数据。';
        }else{
            $res['stat'] = 0;
            $res['data'] = $data;
            $res['msg'] = '查找失败！';
        }
        $res['recordsTotal'] = $res['count'];
        $res['recordsFiltered'] = $res['count'];
        $this->ajaxReturn($res);
    }
}